#!/bin/sh /etc/rc.common

START=99
USE_PROCD=1
PROG=/usr/bin/xunlei

get_config() {
	config_get_bool enabled $1 enabled 0
	config_get_bool debug $1 debug 0
	config_get host $1 host "0.0.0.0"
	config_get port $1 port 5051
	config_get auth_user $1 auth_user ''
	config_get auth_password $1 auth_password ''
	config_get config_path $1 config_path "/opt/xunlei"
	config_get download_path $1 download_path "/opt/xunlei/downloads"
	config_get mount_bind_download_path $1 mount_bind_download_path "/xunlei"
}

start_service() {
	config_load xunlei
	config_foreach get_config xunlei
	[ $enabled -ne 1 ] && return 1

	if [ ! -d "/usr/share/xunlei/target/var" ]; then
		path="/usr/share/xunlei/target/host/etc"
		mkdir -p $path
		id=$(cat /proc/sys/kernel/random/uuid | cut -c1-7)
		echo "unique=\"synology_${id}_720+\"" >$path/synoinfo.conf
		chmod 755 $path/synoinfo.conf

		path="/usr/share/xunlei/target/host/usr/syno/synoman/webman/modules"
		mkdir -p $path
		mkdir -p /usr/syno/synoman/webman/modules
		echo -e '#!/usr/bin/env sh\necho OK' >$path/authenticate.cgi
		chmod 755 $path/authenticate.cgi
	fi

	if [ -f /etc/synoinfo.conf ]; then
		rm /etc/synoinfo.conf
	fi

	if [ -f /usr/syno/synoman/webman/modules/authenticate.cgi ]; then
		rm /usr/syno/synoman/webman/modules/authenticate.cgi
	fi

	rm -rf /var/packages/pan-xunlei-com
	mkdir -p /var/packages/pan-xunlei-com
	ln -s /usr/share/xunlei/target /var/packages/pan-xunlei-com
	ln -s /usr/share/xunlei/target/host/etc/synoinfo.conf /etc/synoinfo.conf
	ln -s /usr/share/xunlei/target/host/usr/syno/synoman/webman/modules/authenticate.cgi /usr/syno/synoman/webman/modules/authenticate.cgi

	if [ ! -d "$config_path" ]; then
		mkdir -p $config_path
	fi

	if [ ! -d "$download_path" ]; then
		mkdir -p $download_path
	fi

	if [ ! -d "$mount_bind_download_path" ]; then
		mkdir -p $mount_bind_download_path
	fi
	
	args="--host $host --port $port --config-path $config_path --download-path $download_path --mount-bind-download-path $mount_bind_download_path"

	if [ -n "$auth_user" ] && [ -n "$auth_password" ]; then
		args="$args --auth-user $auth_user --auth-password $auth_password"
	fi

	if [ $debug -ne 0 ]; then 
		args="$args --debug"
	fi
	
	procd_open_instance
	procd_set_param command /bin/sh -c "$PROG launcher $args >>/var/log/xunlei.log 2>&1"
	procd_set_param stdout 0
	procd_set_param stderr 0
	procd_set_param pidfile /var/run/xunlei.pid
	procd_close_instance
}

service_triggers() {
	procd_add_reload_trigger "xunlei"
}

reload_service() {
	stop
	for i in $(seq 1 60); do
		if [ -z "$(ps -ef | grep xunlei | grep -v grep | grep -v $$ | grep -v '/etc/rc.common' | grep -v '/sbin/service' | grep -v '/sbin/luci-reload')" ]; then
			break
		fi
		sleep 1
	done
	start
}
